<template>
    <view class="wrapper">
        <view class="form-item">
			<uni-view style="margin-bottom: 15px;">
			  <text>请选择运营城市：</text>
			</uni-view>
            <input v-model="searchStr" placeholder="请输入关键词搜索" @focus="showList = true" @blur="showList = false"/>
        </view>
        <view class="city-list" v-show="showList">
            <view class="city-item" v-for="item in filterList" :key="item.adcode" @mousedown="handleCity(item)">
                <text @click="handleCity(item)">{{item.name}}</text>
            </view>
        </view>
        <button class="submit-btn" @click="handleSubmit">提交</button>
    </view>
</template>

<script setup>
import { onMounted, ref, computed, nextTick } from "vue";
import { useStore } from "vuex";
import gdMapConf from "../config/gdMapConf";

const $store = useStore();

let cityList = ref([]);
let searchStr = ref('');
let selectedCityAdcode = ref(''); // 用于保存选中的城市adcode
let showList = ref(false); // 控制城市列表显示的状态
let filterList = computed(()=>{
    return cityList.value.filter(i=> i.name.includes(searchStr.value))
});

onMounted(()=>{
    getCityList()
})

const getCityList = () =>{
    uni.request({
        method: 'GET',
        url: `${gdMapConf.cityApiUrl}?subdistrict=2&key=${gdMapConf.cityKey}`,
        success(res){
            cityList.value = formatCity(res.data.districts[0].districts).sort((a,b)=>{
                return a.name.localeCompare(b.name, 'zh-CN');
            });
        }
    })
};

const formatCity = (data)=>{
    let arr = [];
    data.forEach(i => {
        if(i.citycode.length){
            arr.push(i);
        }
        if(i.districts.length){
            arr = arr.concat(formatCity(i.districts))
        }
    });
    return arr;
}

const handleCity = (item) => {
	nextTick(() => {
		console.log('城市被点击:', item);
		searchStr.value = item.name;
		selectedCityAdcode.value = item.adcode;
		showList.value = false;
	});
    
};

const handleSubmit = () => {
    if(selectedCityAdcode.value) {
        // 这里执行提交逻辑，提交selectedCityAdcode
        console.log('提交的城市adcode:', selectedCityAdcode.value);
        // 可以在这里调用提交的API
    } else {
        console.log('请选择一个城市');
    }
}
</script>
<style lang="scss" scoped>
.wrapper{
    padding: $uni-spacing-max;
}
.form-item {
    margin-bottom: 20px;
}

input {
	padding: 10px;
	border: 1px solid #ccc;
	border-radius: 5px;
}

.city-item{
    height: 70rpx;
    line-height: 70rpx;
    font-size: $uni-font-size-base;
    border-bottom: 1px solid #eee;
}
.submit-btn {
    background-color: #007bff;
    color: #fff;
    border: none;
    border-radius: 5px;
    cursor: pointer;
  }
</style>
